//
//  ManhuaViewController.m
//  Double
//
//  Created by 孟令博 on 15/5/22.
//  Copyright (c) 2015年 袁庆秋. All rights reserved.
//

#import "ManhuaViewController.h"
#import "ManHuaCell.h"
#import <AFNetworking/AFHTTPRequestOperationManager.h>
#import "ManHuaModel.h"
#import <UIImageView+WebCache.h>
#import "ManHuaClassifyViewController.h"
#import "MJRefresh.h"
#import "ManHuaPlayerViewController.h"


@interface ManhuaViewController ()<UITableViewDelegate,UITableViewDataSource>
//存放model的数组
@property (nonatomic, retain) NSMutableArray *bigArray;
@property (nonatomic, assign) int i;


@end


@implementation ManhuaViewController
- (void)dealloc
{
    [_bigArray release];
    [_table1 release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.bigArray = [NSMutableArray array];
        self.i = 2;

    }
    return self;
}

#pragma mark -
#pragma mark 请求数据
- (void)startConnection
{
    AFHTTPRequestOperationManager *m = [AFHTTPRequestOperationManager manager];
    m.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *str = [NSString stringWithFormat:@"http://manhua.haomee.cn/?m=Cartoon&ios=23&pad=0&a=index&tab=0&page=1&limit=15"];
    m.responseSerializer = [AFHTTPResponseSerializer serializer];
    [m GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:   NSJSONReadingMutableContainers error:nil];
        
        NSArray *bigArray = [dic objectForKey:@"list"];
        for (NSDictionary *dic in bigArray) {
//            NSLog(@"%@", dic);
            ManHuaModel *model = [[ManHuaModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_bigArray addObject:model];
            [model release];
        }
        [_table1 reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
}

- (void)MyTableView
{
    self.table1 = [[ADCustomTableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 110) style:UITableViewStylePlain];
//设置代理人
    _table1.dataSource = self;
    _table1.delegate = self;
    self.table1.separatorStyle = UITableViewCellStyleDefault;
//设定tableView重用池
    [self.table1 registerClass:[ManHuaCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_table1];
//设定上啦加载 下拉刷新
    [self.table1 addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(loadNewData:)];
    [self.table1 addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [_table1 release];
    
    [[UIApplication sharedApplication] setStatusBarHidden:TRUE];
}
//下拉刷新点击事件
- (void)loadNewData:(id)sender
{
//    self.i = 2;
//    [self.bigArray removeAllObjects];
//    [self.table1 reloadData];
    
    [self startConnection];
    [self.table1.header endRefreshing];
}
//上啦加载点击事件
- (void)loadMoreData
{
//网络请求 page值 i++
    AFHTTPRequestOperationManager *m = [AFHTTPRequestOperationManager manager];
    m.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *str = [NSString stringWithFormat:@"http://manhua.haomee.cn/?m=Cartoon&ios=23&pad=0&a=index&tab=0&page=%d&limit=15",self.i];
    [m GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:   NSJSONReadingMutableContainers error:nil];
        
        NSArray *bigArray = [dic objectForKey:@"list"];
        if (bigArray.count == 0) {
            [self.table1 removeFooter];
            return;
        }
        for (NSDictionary *dic in bigArray) {
            //            NSLog(@"%@", dic);
            ManHuaModel *model = [[ManHuaModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.bigArray addObject:model];
            [model release];
        }
        [self.table1 reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];

    // 拿到当前的上拉刷新控件，结束刷新状态
    
    self.i += 1;
    [self.table1.footer endRefreshing];
    
}
#pragma mark -
#pragma mark tableView协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
        return [self.bigArray count];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 //cell重用池
    ManHuaCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
//cell赋值
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    ManHuaModel *model = [self.bigArray objectAtIndex:indexPath.row];
    [cell.image sd_setImageWithURL:[NSURL URLWithString:model.pic] placeholderImage:[UIImage imageNamed:@"placeholder.jpg"] options:SDWebImageRetryFailed];
    [cell.lable1 setText:model.name];
    [cell.lable2 setText:model.lastup];
    
    return cell;
    
}
//cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 160;
}
//cell的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    ManHuaPlayerViewController *player = [[ManHuaPlayerViewController alloc] init];
    ManHuaModel *model = [self.bigArray objectAtIndex:indexPath.row];
    player.iD = model.myId;
    player.episode = model.lastup;
    player.navigationItem.title = model.name;
    player.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:player animated:YES];
    
    [player release];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self MyTableView];
    [self startConnection];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
